const API_BASE_URL = 'http://localhost:8080/api'; // 生产环境API地址

class ApiClient {
    constructor() {
        this.baseURL = API_BASE_URL;
        this.token = wx.getStorageSync('auth_token') || '';
        this.encryptionKey = ''; // 初始为空

        // 尝试从本地存储获取
        this.loadEncryptionKey();
    }

    // 从本地安全存储加载密钥
    loadEncryptionKey() {
        try {
            const storedKey = wx.getStorageSync('encryption_key');
            if (storedKey) {
                this.encryptionKey = storedKey;
            }
        } catch (error) {
            console.error('加载加密密钥失败:', error);
        }
    }

    // 设置认证令牌
    setToken(token) {
        this.token = token;
        wx.setStorageSync('auth_token', token);
    }

    // 清除认证令牌
    clearToken() {
        this.token = '';
        wx.removeStorageSync('auth_token');
    }

    // 通用请求方法
    async request(url, options = {}) {
        const {
            method = 'GET',
            data = {},
            headers = {},
            showLoading = true
        } = options;

        if (showLoading) {
            wx.showLoading({
                title: '加载中...',
                mask: true
            });
        }

        try {
            const requestHeaders = {
                'Content-Type': 'application/json',
                'x-encryption-key': this.encryptionKey,
                ...headers
            };

            if (this.token) {
                requestHeaders['Authorization'] = `Bearer ${this.token}`;
            }

            const response = await new Promise((resolve, reject) => {
                wx.request({
                    url: `${this.baseURL}${url}`,
                    method,
                    data,
                    header: requestHeaders,
                    success: resolve,
                    fail: reject
                });
            });

            if (showLoading) {
                wx.hideLoading();
            }

            if (response.statusCode === 200) {
                return response.data;
            } else if (response.statusCode === 401) {
                // 令牌过期，清除本地存储
                this.clearToken();
                wx.showToast({
                    title: '登录已过期，请重新登录',
                    icon: 'none'
                });
                return null;
            } else {
                throw new Error(response.data.message || '请求失败');
            }
        } catch (error) {
            if (showLoading) {
                wx.hideLoading();
            }

            wx.showToast({
                title: error.message || '网络错误',
                icon: 'none'
            });

            throw error;
        }
    }

    // 登录时获取加密密钥
    async login(openid, userInfo) {
        try {
            const response = await this.request('/users/login', {
                method: 'POST',
                data: { openid, userInfo }
            });

            if (response && response.success) {
                // 服务器返回加密密钥
                if (response.data.encryptionKey) {
                    this.encryptionKey = response.data.encryptionKey;
                    // 安全存储到本地
                    wx.setStorageSync('encryption_key', this.encryptionKey);
                }

                // 存储访问令牌
                this.setToken(response.data.token);
            }

            return response;
        } catch (error) {
            console.error('登录失败:', error);
            throw error;
        }
    }
    // 获取或刷新加密密钥
    async getEncryptionKey() {
        if (!this.encryptionKey) {
            try {
                const response = await this.request('/users/encryption-key', {
                    method: 'GET'
                });

                if (response && response.success) {
                    this.encryptionKey = response.data.encryptionKey;
                    wx.setStorageSync('encryption_key', this.encryptionKey);
                }
            } catch (error) {
                console.error('获取加密密钥失败:', error);
                throw error;
            }
        }

        return this.encryptionKey;
    }

    // 获取用户信息
    async getUserProfile() {
        return this.request('/users/profile');
    }

    // 更新用户信息
    async updateUserProfile(userInfo) {
        return this.request('/users/profile', {
            method: 'PUT',
            data: { userInfo }
        });
    }

    // 保存隐私数据
    async savePrivacyData(dataType, content) {
        return this.request('/users/privacy-data', {
            method: 'POST',
            data: { dataType, content }
        });
    }

    // 获取隐私数据
    async getPrivacyData(dataType) {
        return this.request(`/users/privacy-data/${dataType}`);
    }

    // 删除账户
    async deleteAccount() {
        return this.request('/users/account', {
            method: 'DELETE'
        });
    }
}

module.exports = new ApiClient();